<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    width="500px"
    @update:model-value="$emit('update:visible', $event)"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="left"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入部门名称"
          clearable
        />
      </el-form-item>

      <el-form-item label="上级部门" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          :data="departmentOptions"
          :props="treeProps"
          placeholder="请选择上级部门"
          clearable
          check-strictly
          :render-after-expand="false"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="部门类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio value="company">公司</el-radio>
          <el-radio value="department">部门</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 部门数据接口
interface Department {
  id: number
  name: string
  parentId?: number
  type: 'company' | 'department'
  userCount: number
  children?: Department[]
}

// Props
interface Props {
  visible: boolean
  title: string
  formData: Partial<Department>
  departments: Department[]
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  submit: [data: Partial<Department>]
  cancel: []
}>()

// 表单引用
const formRef = ref()

// 表单数据
const form = ref<Partial<Department>>({
  name: '',
  parentId: undefined,
  type: 'department'
})

// 树形选择器配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 部门选项（排除当前编辑的部门）
const departmentOptions = computed(() => {
  const filterDepartments = (depts: Department[]): Department[] => {
    return depts.filter(dept => dept.id !== form.value.id).map(dept => ({
      ...dept,
      children: dept.children ? filterDepartments(dept.children) : undefined
    }))
  }
  return filterDepartments(props.departments)
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '部门名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择部门类型', trigger: 'change' }
  ]
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      form.value = { ...newData }
    }
  },
  { immediate: true, deep: true }
)

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    emit('submit', { ...form.value })
  } catch (error) {
    ElMessage.error('请检查表单输入')
  }
}

// 取消操作
const handleCancel = () => {
  emit('cancel')
}

// 关闭弹窗
const handleClose = () => {
  emit('cancel')
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #374151;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}
</style>
